<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\command;

use app\enum\CdcEnum;
use app\enum\CostServiceCostEnum;
use app\model\CostTaskAccountCompareModel;
use app\service\cdc\cost\TaskAccountService;
use think\console\Input;
use think\console\Output;
use think\facade\Cache;

class CostMediaCostCompareListWork extends BaseWork
{
    /**
     * @var int redis-key
     */
    public const REDIS_TASK_KEY = CostServiceCostEnum::CACHE_CONFIG['media_cost_compare_list'];

    /**
     * @var int 最大页数
     */
    public const MAX_PAGE = 50;

    /**
     * @var int 当前页数
     */
    public int $currPage = 0;

    protected function configure()
    {
        // 指令配置
        $this->setName('cost_media_cost_compare_list_work');
        // 设置参数
        $this->setDescription('存储回溯数据结果处理脚本队列脚本')
            ->setHelp('php think cost_media_cost_compare_list_work');
    }

    protected function execute(Input $input, Output $output)
    {
        set_time_limit(0);
        $this->getOutputMessage('存储回溯数据结果处理脚本队列开始');
        $redis = Cache::store('redis')->handler();

        $where = [
            ['new_task_account_id', '>', 0],
            ['new_stat_date', '<', intval(date('Ymd'))],
        ];

        // 超过5min就停止
        $t = time();
        $runTime = 5 * 60;
        while (time() - $t <= $runTime) {
            (new CostTaskAccountCompareModel())->where($where)->chunk(200, function ($items) use ($redis) {
                if ($this->currPage > self::MAX_PAGE) {
                    return false;
                }

                if (! $items) {
                    return false;
                }

                try {
                    foreach ($items as $item) {
                        // 存入redis队列
                        $res = $redis->rPush(self::REDIS_TASK_KEY, $item->getKey());
                        if (! $res) {
                            $this->getOutputMessage('存储回溯数据结果处理脚本队列失败,报表id:' . $item->getKey() . TaskAccountService::getError(0));
                        }
                    }
                } catch (\Exception $e) {
                    $this->getOutputMessage($e->getMessage());
                }
                ++$this->currPage;
            }, 'id', 'ASC');
            sleep(rand(5, 10));
        }
        $this->getOutputMessage('存储回溯数据结果处理脚本队列结束');
    }
}
